import React,{useEffect,useState} from "react";
import { Text, View,StyleSheet,TouchableHighlight,TouchableOpacity, Linking,ScrollView, Alert,TextInput,Platform ,Image} from "react-native";
import * as S from "../Home/styles";
import { Avatar, HStack, Center, NativeBaseProvider ,ChevronRightIcon,useToast,ArrowBackIcon} from "native-base";
import {launchImageLibrary,launchCamera} from 'react-native-image-picker';
import { /*RFValue*/ } from "react-native-responsive-fontsize";
import Icon from 'react-native-vector-icons/Ionicons';
import { useGlobal } from '../../utils/GlobalContext';
import { getUeser,phoneLogin,getCode,register } from "../../services/user";
import { CommonActions } from '@react-navigation/native';
import { showToast } from "../../utils/toast";
import Spinner from 'react-native-loading-spinner-overlay';

const Loading = ({ loading, text }) => {
  // if (!loading) {
  //   return null;
  // }

  return (<Spinner
    visible={loading}
    textContent={text}
    cancelable={true}
    // customIndicator={ <Spinner2 size="lg" /> }
    // indicatorStyle={{margin:0,marginBottom:0}}
    overlayColor={'rgba(0, 0, 0, 0.5)'}
    textStyle={{ color: '#FFF',fontSize:16,fontFamily:'HarmonyOS Sans SC',fontWeight:'700' }}
    animation="fade"
  />
  );
};


const Title = ({navigation}:any)=>{
  return(
    <View style={styles.titleBox}>
      <TouchableOpacity
        style={styles.backBtn}
        onPress={() => {
          navigation.goBack()
        }}
      >
        <ArrowBackIcon size="5" />
      </TouchableOpacity>
    </View>
  )
}

const LoginBox = ({route,navigation,setLoading}:any)=>{

  const { state, dispatch } = useGlobal();
  const toast = useToast();

  const [username,setUsername] = useState('')
  const [code,setCode] = useState('')
  const [password,setPawssword] = useState('')

  const [count,setCount] = useState(0)

  const onChange = (text:any,type:number)=>{
    if(type == 1){
      setUsername(text)
    }else if(type == 2){
      setCode(text)
    }else{
      setPawssword(text)
    }
  }

  const sendCode =()=>{
    if(!username){
      // toast.show({
      //   description: "请输入手机号或邮箱",
      //   placement: "top"
      // })
      showToast("", "", "请输入手机号或邮箱");
      return
    }
    let obj = {
      phone:username
    }
    getCode(obj).then(res=>{
      countDownTimer()
    })
  }

  const countDownTimer = ()=>{
    setCount(60)
    let seconds = 60;
    const countdown = () => {
      if (seconds > 0) {
        seconds--;
        setCount(seconds)
      } else {
        clearInterval(timer); // 清除定时器
        setCount(0)
      }
    };
    const timer = setInterval(countdown, 1000);
  }



  const phoneSignBtn = ()=>{
    let obj = {
      username,
      code,
      password,
    }
    if(!username){
      // toast.show({
      //   description: "请输入手机号",
      //   placement: "top"
      // })
      showToast("", "", "请输入手机号");
      return
    }
    if(!code){
      // toast.show({
      //   description: "请输入验证码",
      //   placement: "top"
      // })
      showToast("", "", "请输入验证码");
      return
    }
    if(!password){
      // toast.show({
      //   description: "请输入密码",
      //   placement: "top"
      // })
      showToast("", "", "请输入密码");
      return
    }
    setLoading(true)
    register(obj).then((res:any)=>{
      console.log(res)
      setLoading(false)
      dispatch({ type:'SET_TOKEN' , payload:res.data.token })
      dispatch({ type:'SET_USER' , payload:{} })
      getUserInfo()
      // navigation.replace('Home')
      navigation.dispatch(
        CommonActions.reset({
          index: 0,
          routes: [{ name: 'Home' }] // 设置新页面的路由
        })
      );
    }).catch(()=>{
      setLoading(false)
    })

    const getUserInfo = ()=>{
      getUeser().then((res:any)=>{
        dispatch({ type:'SET_USER' , payload:res.data })
      })
    }




    // navigation.navigate('CodeLoginCheck',{userna me})
  
    // phoneLogin(obj).then(res=>{
    //   // console.log(res)
    //   getUserInfo(res.data.token,res.data.userId)
    //   dispatch({ type:'SET_TOKEN' , payload:res.data.token })
    //   dispatch({ type:'SET_USER' , payload:{} })
    //   navigation.replace('Home')
    // })
  }

  return(
    <View style={styles.loginBox}>
      <View style={styles.titleContent}>
        <Text style={styles.contentOne}>重置密码</Text>
     </View>
      <View style={styles.boxInput}>
        <View>
          <TextInput
            style={styles.input}
            placeholder='手机号或邮箱'
            placeholderTextColor='#8E8E93'
            onChangeText={text => onChange(text,1)}
            value={username}
          />
        </View>
        <View style={styles.inputBox}>
          <TextInput
            style={styles.input}
            placeholder='验证码'
            keyboardType="numeric"
            maxLength={6}
            placeholderTextColor='#8E8E93'
            onChangeText={text => onChange(text,2)}
            value={code}
          />

          {
            count > 0
            ?
            <View style={styles.btnBox}>
              <Text style={styles.btnText}>{count}s</Text>
            </View>
            :
            <TouchableOpacity
              onPress={() => {
                sendCode()
              }}
            >
              <View style={styles.btnBox}>
                <Text style={styles.btnText}>发送验证码</Text>
              </View>
            </TouchableOpacity>
          }
          
          
        </View>
        <View>
          <TextInput
            style={styles.input}
            placeholder='密码'
            textContentType='password'
            secureTextEntry={true}
            placeholderTextColor='#8E8E93'
            onChangeText={text => onChange(text,3)}
            value={password}
          />
        </View>

        <View>

          <TouchableOpacity style={[styles.loginBtn,{backgroundColor:'#4371B1'}]} onPress={() => {
              phoneSignBtn()
          }}>
            <Text style={[styles.loginBtnText,{color:'#fff'}]}>确认</Text>
          </TouchableOpacity>
          
        </View>
      </View>
    </View>
  )
}


const Login = ({route,navigation}:any) => {
  const [ loading,setLoading ] = useState(false)
  return (
    <S.GrayContainer style={{backgroundColor:'#FFFFFF'}}>
      <NativeBaseProvider>
       <View style={styles.container}>
          <Title navigation={navigation}/>
          <ScrollView style={{height:'55%'}} showsVerticalScrollIndicator={false}>
            <LoginBox setLoading={setLoading} route={route} navigation={navigation}/>
          </ScrollView>
       </View>
       <Loading loading={loading} text={'登录中...'}/>
      </NativeBaseProvider>
      
    </S.GrayContainer>
  );
};


export default Login;
const styles = StyleSheet.create({
  container:{
    height:"100%",
    width:'100%',
    // alignItems:'center',
    paddingHorizontal:24,
    
  },
  titleBox:{
    width:'100%',
    position:'relative',
    alignItems:'center',
    height:40,
    justifyContent:"center",
    marginBottom:26,
  },
  backBtn:{
    position:'absolute',
    left:0,
    backgroundColor:'#fff',
    width:40,
    height:40,
    display:'flex',
    alignItems:'center',
    justifyContent:'center',
    borderRadius:100,
    
    shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    elevation: 3, // 阴影深度
  },
  loginBox:{
    paddingTop:20,
  },
  titleContent:{
  },
  contentOne:{
    fontSize:28,
    fontWeight:'500',
    color:'#000000',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    // marginBottom:8,
  },
  contentTwo:{
    fontSize:14,
    fontWeight:'400',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    color:'#8E8E93',
    marginBottom:18,
  },
  boxInput:{
    marginTop:68,
  },
  input:{
    fontSize:16,
    borderBottomColor:'#F2F2F7',
    borderBottomWidth:1,
    paddingVertical:12,
    marginBottom:16,
    color:'#000',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
  },
  agreementBox:{
    flexDirection:'row',
    marginTop:34,
    alignItems:'center',
  },
  agreementBoxCheck:{
    flexDirection:'row'
  },
  agreementBoxCheckText:{
    color:'#8E8E93',
    fontSize:12,
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    lineHeight:18
  },
  agreementBoxView:{},
  agreementBoxViewText:{
    fontSize:12,
    lineHeight:18,
    color:'#4371B1',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
  },
  loginBtn:{
    width:'100%',
    alignItems:'center',
    justifyContent:'center',
    height:44,
    borderRadius:10,
    marginTop:18,
    overflow:'hidden'
  },
  loginBtnText:{
    fontSize:14,
    fontWeight:'500',
  },
  btnBottom:{
    flexDirection:'row',
    justifyContent:'space-between',
    marginTop:20,
  },
  btnBottomText:{
    fontSize:14,
    color:'#4371B1',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
  },
  wxLoginBox:{
    flex:1,
    alignItems:'center',
    paddingTop:20,
  },
  textBox:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'center',
    marginBottom:22,
  },
  boxLine:{
    width:80,
    height:1,
    backgroundColor:'#E5E5EA',
  },
  otherLoginText:{
    fontSize:12,
    color:'#8E8E93',
    paddingHorizontal:16,
  },
  inputBox:{
    position:'relative',
    width:'100%',
  },
  btnBox:{
    position:'absolute',
    justifyContent:'center',
    right:0,
    bottom:0,
    paddingBottom:30,
    // height:30,
    // marginTop:8,
  },
  btnText:{
    fontSize:16,
    color:'#4371B1',
    fontFamily:'HarmonyOS Sans SC',
    fontWeight:'700'
  }


})
